import React, { memo, useCallback, useState } from 'react';
import { Modal, Alert, List, Button, Space, Radio, Input, Form } from 'antd';
import { ExclamationCircleOutlined, WarningOutlined, CloseCircleOutlined } from '@ant-design/icons';
import type { IScheduleConflictDialogProps, IConflictResolution } from '@/types/components/schedule';
import styles from './ScheduleConflictDialog.module.css';

/**
 * 课表冲突对话框组件
 * @description 显示课程安排冲突信息，并提供解决方案选择
 */
const ScheduleConflictDialog: React.FC<IScheduleConflictDialogProps> = memo(({
  conflicts,
  visible,
  onResolve,
  onCancel,
  originalData,
  className
}) => {
  const [resolutionType, setResolutionType] = useState<'ignore' | 'modify' | 'cancel'>('cancel');
  const [form] = Form.useForm();

  // 处理解决方案确认
  const handleResolve = useCallback(async () => {
    try {
      let resolution: IConflictResolution;

      switch (resolutionType) {
        case 'ignore':
          resolution = {
            type: 'ignore',
            description: '忽略冲突，强制创建课程安排'
          };
          break;
        
        case 'modify':
          const values = await form.validateFields();
          resolution = {
            type: 'modify',
            modifiedData: values,
            description: '修改时间以避免冲突'
          };
          break;
        
        case 'cancel':
        default:
          resolution = {
            type: 'cancel',
            description: '取消创建课程安排'
          };
          break;
      }

      onResolve(resolution);
    } catch (error) {
      console.error('解决冲突失败:', error);
    }
  }, [resolutionType, form, onResolve]);

  // 获取冲突严重程度图标
  const getSeverityIcon = (severity: 'warning' | 'error') => {
    return severity === 'error' ? 
      <CloseCircleOutlined className={styles.errorIcon} /> :
      <WarningOutlined className={styles.warningIcon} />;
  };

  // 渲染冲突列表
  const renderConflictList = () => (
    <List
      className={styles.conflictList}
      dataSource={conflicts}
      renderItem={(conflict, index) => (
        <List.Item className={styles.conflictItem}>
          <div className={styles.conflictContent}>
            <div className={styles.conflictHeader}>
              {getSeverityIcon(conflict.severity)}
              <span className={styles.conflictType}>
                {conflict.type === 'time' && '时间冲突'}
                {conflict.type === 'student' && '学生冲突'}
                {conflict.type === 'teacher' && '教师冲突'}
                {conflict.type === 'classroom' && '教室冲突'}
              </span>
            </div>
            <div className={styles.conflictMessage}>
              {conflict.message}
            </div>
            {conflict.conflictInstances.length > 0 && (
              <div className={styles.conflictInstances}>
                <span className={styles.instancesLabel}>冲突课程：</span>
                {conflict.conflictInstances.map((instance, idx) => (
                  <span key={instance.id} className={styles.instanceInfo}>
                    {instance.date} {instance.startTime}-{instance.endTime}
                    {idx < conflict.conflictInstances.length - 1 && '，'}
                  </span>
                ))}
              </div>
            )}
          </div>
        </List.Item>
      )}
    />
  );

  // 渲染解决方案选项
  const renderResolutionOptions = () => (
    <div className={styles.resolutionSection}>
      <h4 className={styles.resolutionTitle}>请选择解决方案：</h4>
      <Radio.Group
        value={resolutionType}
        onChange={(e) => setResolutionType(e.target.value)}
        className={styles.resolutionOptions}
      >
        <Space direction="vertical" size="middle">
          <Radio value="cancel" className={styles.resolutionOption}>
            <div className={styles.optionContent}>
              <span className={styles.optionTitle}>取消创建</span>
              <span className={styles.optionDescription}>
                取消本次课程安排的创建，返回修改
              </span>
            </div>
          </Radio>
          
          <Radio value="ignore" className={styles.resolutionOption}>
            <div className={styles.optionContent}>
              <span className={styles.optionTitle}>忽略冲突</span>
              <span className={styles.optionDescription}>
                强制创建课程安排，忽略时间冲突警告
              </span>
            </div>
          </Radio>
          
          <Radio value="modify" className={styles.resolutionOption}>
            <div className={styles.optionContent}>
              <span className={styles.optionTitle}>修改时间</span>
              <span className={styles.optionDescription}>
                修改课程时间以避免冲突
              </span>
            </div>
          </Radio>
        </Space>
      </Radio.Group>

      {/* 修改时间表单 */}
      {resolutionType === 'modify' && (
        <div className={styles.modifyForm}>
          <Form
            form={form}
            layout="vertical"
            initialValues={originalData}
            className={styles.form}
          >
            <div className={styles.formRow}>
              <Form.Item
                name="startTime"
                label="新的开始时间"
                rules={[{ required: true, message: '请输入开始时间' }]}
                className={styles.halfWidth}
              >
                <Input placeholder="HH:mm" />
              </Form.Item>
              
              <Form.Item
                name="endTime"
                label="新的结束时间"
                rules={[{ required: true, message: '请输入结束时间' }]}
                className={styles.halfWidth}
              >
                <Input placeholder="HH:mm" />
              </Form.Item>
            </div>
          </Form>
        </div>
      )}
    </div>
  );

  return (
    <Modal
      title={
        <div className={styles.modalTitle}>
          <ExclamationCircleOutlined className={styles.titleIcon} />
          课程安排冲突
        </div>
      }
      open={visible}
      onCancel={onCancel}
      footer={
        <Space>
          <Button onClick={onCancel}>
            取消
          </Button>
          <Button
            type="primary"
            onClick={handleResolve}
            danger={resolutionType === 'ignore'}
          >
            {resolutionType === 'cancel' && '确认取消'}
            {resolutionType === 'ignore' && '强制创建'}
            {resolutionType === 'modify' && '修改并创建'}
          </Button>
        </Space>
      }
      width={600}
      className={`${styles.conflictDialog} ${className || ''}`}
      destroyOnHidden
    >
      <div className={styles.dialogContent}>
        <Alert
          message={`检测到 ${conflicts.length} 个冲突`}
          description="请仔细查看冲突详情，并选择合适的解决方案。"
          type="warning"
          showIcon
          className={styles.summaryAlert}
        />

        {renderConflictList()}
        {renderResolutionOptions()}
      </div>
    </Modal>
  );
});

ScheduleConflictDialog.displayName = 'ScheduleConflictDialog';

export default ScheduleConflictDialog;